package sz.szsmk.citizencard.ui.dzsmkfragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chenenyu.router.annotation.Route;
import com.ogaclejapan.smarttablayout.SmartTabLayout;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItemAdapter;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItems;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.entity.BillFilterBean;
import sz.szsmk.citizencard.model.network.dzbean.req.BillRequest;
import sz.szsmk.citizencard.model.network.dzbean.res.BillResponse;
import sz.szsmk.citizencard.model.network.dzbean.res.PreAuthResult;
import sz.szsmk.citizencard.mvp.BasePresenter;
import sz.szsmk.citizencard.mvp.BillMvpView;
import sz.szsmk.citizencard.mvp.dzsmkpresenter.BillPresenter;
import sz.szsmk.citizencard.ui.dzsmkavtivity.BillFilterActivity;
import sz.szsmk.citizencard.widget.GlobalVariables;


/**
 * Created by chensf on 17/9/30.
 *  账单
 */
@Route("dzsmkbill")
public class BillFragment extends AppBaseFragment implements OnFragmentRefresh, BillMvpView {


    RecyclerView rv_qr_bill;

    RelativeLayout rl_qr_norecord;

    TextView tv_filter;

    List<BillResponse.DataBean.TradeListBean.ItemBean> billItemList = new ArrayList<>();

    private LinearLayoutManager linearLayoutManager;
    @Inject
    BillPresenter billPresenter;

    int currentPage = 0;
    private int type = 2;
    private int pageNumber = 0;
    private BaseQuickAdapter billAdapter;
    private String lastMonth = "";

    //请求参数
    BillRequest billRequest;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.qr_fragment_bill, container, false);
        getComponent().inject(this);

        rv_qr_bill = view.findViewById(R.id.rv_qr_bill);

        rl_qr_norecord = view.findViewById(R.id.rl_qr_norecord);

        tv_filter = view.findViewById(R.id.tv_filter);


        viewPager = view.findViewById(R.id.viewpager);

        viewpagertab = view.findViewById(R.id.viewpagertab);



        billRequest = new BillRequest();
        return view;
    }

    public static BillFragment getInstance() {
        BillFragment sf = new BillFragment();
        return sf;
    }


    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        EventBus.getDefault().register(this);
        initView();
        initData(2);
    }

    public void initData(int tradeType) {
        PreAuthResult preAuthResult = GlobalVariables.getInstance(getContext()).getPreAuthResult();
        if (preAuthResult == null) {
            return;
        }
        pageNumber = 1;
        lastMonth = "";
        type = tradeType;
        billItemList.clear();
        billAdapter.setNewData(null);

        //设置参数 请求接口
        billRequest.setPageSize(10);
        billRequest.setPageNumber(pageNumber);
        billRequest.setTradeType(type+"");
        billPresenter.getBillList(billRequest);

        tv_filter.setOnClickListener(v->{
            Intent intent = new Intent(getContext(),BillFilterActivity.class);
            startActivity(intent);
        });
    }

    @Override
    public void onResume() {
        super.onResume();
//        billPresenter.getBillList(type, 10, pageNumber);
    }

    SmartTabLayout viewpagertab;

    ViewPager viewPager;

    private void initView() {

        FragmentPagerItemAdapter adapter = new FragmentPagerItemAdapter(
                getActivity().getSupportFragmentManager(), FragmentPagerItems.with(getContext())
                .add("全部", NullFragment.class)
                .add("收入", NullFragment.class)
                .add("支出", NullFragment.class)
                .create());
        viewPager.setAdapter(adapter);

        viewpagertab.setViewPager(viewPager);

        billAdapter = new BaseQuickAdapter<BillResponse.DataBean.TradeListBean.ItemBean, BaseViewHolder>(R.layout.qr_item_bill, new ArrayList<>()) {
            @Override
            protected void convert(BaseViewHolder helper, BillResponse.DataBean.TradeListBean.ItemBean item) {

                String tradeType = item.getTradeType();
                switch (tradeType){
                    case "0":
                        helper.setText(R.id.tv_qr_recharge,  item.getMoneyDesc());
                        helper.setText(R.id.tv_qr_type, "充值");
                        helper.setImageResource(R.id.iv_qr_icon, R.drawable.qr_recharge);
                        break;
                    case "9":
                    case "A":
                    case "B":
                    case "1":
                        helper.setText(R.id.tv_qr_recharge,  item.getMoneyDesc());
                        helper.setText(R.id.tv_qr_type, "公交车费");
                        helper.setImageResource(R.id.iv_qr_icon, R.drawable.qr_bus_fare);
                        break;
                    case "2":
                        helper.setText(R.id.tv_qr_recharge,  item.getMoneyDesc());
                        helper.setText(R.id.tv_qr_type, "结息");
                        helper.setImageResource(R.id.iv_qr_icon, R.drawable.qr_interest);
                        break;
                        default:
                            helper.setText(R.id.tv_qr_recharge, item.getMoneyDesc());
                            helper.setText(R.id.tv_qr_type, "其他");
                            helper.setImageResource(R.id.iv_qr_icon, R.drawable.qr_interest);
                            break;
                }

                helper.setGone(R.id.ll_qr_month, item.isShowTitle());
                if(!TextUtils.isEmpty(item.getMonth()) &&  (item.getMonth().length()==6)){
                    helper.setText(R.id.tv_qr_month, item.getMonth().substring(0,4)+"年"+item.getMonth().substring(4,6) + "月");
                }

                String time = item.getTime();

                helper.setText(R.id.tv_qr_time, item.getTime());

                String status = "";
                switch (item.getStatus()){
                    case "1":
                        break;
                    case "0":
                        status = "交易失败";
                        break;
                    case "2":
                        status = "交易中";
                        break;
                }
                helper.setText(R.id.tv_qr_statusDesc,item.getRecordTypeStr());
                helper.setText(R.id.tv_qr_status, status);
                helper.setTextColor(R.id.tv_qr_status, item.getStatus().equals("2")? Color.parseColor("#F6A623") : Color.parseColor("#EC5659"));
            }
        };
        billAdapter.openLoadAnimation();
        linearLayoutManager = new LinearLayoutManager(getActivity());
        rv_qr_bill.setLayoutManager(linearLayoutManager);
        rv_qr_bill.setAdapter(billAdapter);


        billAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {

                switch (currentPage){
                    case 0:
                        billRequest.setTradeType("2");
                        break;
                    case 1:
                        billRequest.setTradeType("0");
                        break;
                    case 2:
                        billRequest.setTradeType("1");
                        break;
                }

                billRequest.setPageNumber(pageNumber);
                billPresenter.getBillList(billRequest);

//                billPresenter.getBillList(type, 10, pageNumber);
            }
        }, rv_qr_bill);


        viewpagertab.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                billAdapter.setNewData(new ArrayList<BillResponse.DataBean.TradeListBean.ItemBean>());

                billRequest.setTradeDate(null);
                billRequest.setInType(null);
                billRequest.setOutType(null);

                currentPage = position;
                pageNumber = 1;
                billRequest.setPageNumber(pageNumber);
                switch (position){
                    case 0:
                        billRequest.setTradeType("2");
                        break;
                    case 1:
                        billRequest.setTradeType("0");
                        break;
                    case 2:
                        billRequest.setTradeType("1");
                        break;
                }
                billPresenter.getBillList(billRequest);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    protected BasePresenter[] initPresenters() {
        return new BasePresenter[]{billPresenter};
    }


    @Override
    public void onGetBillSuccess(BillResponse response) {
        List<BillResponse.DataBean.TradeListBean.ItemBean> list = new ArrayList<>();
        BillResponse.DataBean data = response.getData();
        List<BillResponse.DataBean.TradeListBean> tradeListItemList = data.getTradeList();

//        List<TradeListItem> tradeListItemList = response.getTradeList();
//        int size = tradeListItemList.size();
        if (tradeListItemList != null && tradeListItemList.size() > 0) {
            for (BillResponse.DataBean.TradeListBean tradeListItem : tradeListItemList) {
                List<BillResponse.DataBean.TradeListBean.ItemBean> billItems = tradeListItem.getItem();
                String month = tradeListItem.getMonth();
                if (!month.equals(lastMonth)) {
                    billItems.get(0).setShowTitle(true);
                    billItems.get(0).setMonth(month);
                    lastMonth = month;
                }
                list.addAll(billItems);
            }
            billItemList.addAll(list);
        }

        if (billItemList.size() == 0) {
            rl_qr_norecord.setVisibility(View.VISIBLE);
            rv_qr_bill.setVisibility(View.GONE);
        } else {
            rl_qr_norecord.setVisibility(View.GONE);
            rv_qr_bill.setVisibility(View.VISIBLE);
        }

        billAdapter.addData(list);

        billAdapter.loadMoreComplete();

        if (response.getData().getCurrentPage() == response.getData().getTotalPage()) {
            billAdapter.loadMoreEnd();
        } else {
            pageNumber++;
        }
    }


    @Override
    public void onGetBillFail() {

        if (billItemList.size() == 0) {
            rl_qr_norecord.setVisibility(View.VISIBLE);
            rv_qr_bill.setVisibility(View.GONE);
        } else {
            rl_qr_norecord.setVisibility(View.GONE);
            rv_qr_bill.setVisibility(View.VISIBLE);
        }
    }


    @Override
    protected CharSequence getTopTitle() {
        return getString(R.string.qr_my_bill);
    }

    @Override
    public void onRefresh() {
        initData(2);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void onEventMainThread(BillFilterBean billFilterBean) {
        billAdapter.setNewData(new ArrayList<BillResponse.DataBean.TradeListBean.ItemBean>());

        billRequest.setTradeDate(billFilterBean.getTradeDate());
        billRequest.setInType(billFilterBean.getInType());
        billRequest.setOutType(billFilterBean.getOutType());

        billPresenter.getBillList(billRequest);
    }
}